package com.android.nearshop.app.activity.search;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.nearshop.R;
import com.android.nearshop.app.MyApplication;
import com.android.nearshop.app.activity.common.TemplateActivity;
import com.android.nearshop.app.activity.main.FilterActivity;
import com.android.nearshop.app.activity.main.MainIndexActivity;
import com.android.nearshop.app.adapter.listadapter.CommonListAdapter;
import com.android.nearshop.app.adapter.listadapter.KeywordAdapter;
import com.android.nearshop.app.widget.TitleBar;
import com.android.nearshop.app.widget.TitleBar.OnTitleClickListener;
import com.android.nearshop.business.location.MyBMapManager;
import com.android.nearshop.io.database.SearKeyDB;
import com.android.nearshop.io.database.ShopDB;
import com.android.nearshop.io.protocol.in.FindShopAction;
import com.android.nearshop.io.protocol.out.Area;
import com.android.nearshop.io.protocol.out.Shop;
import com.android.nearshop.io.protocol.out.ShopDetail;
import com.android.nearshop.io.protocol.out.ShopList;
import com.android.nearshop.util.Constant;
import com.android.nearshop.util.DataCache;

/*********************************************************
 * @author : huangyue
 * @version : 2012-8-11
 * @see : Searh查询结果界面
 * @test: OK
 * @Copyright : copyrights reserved by personal 2007-2012
 **********************************************************/
public class SearchActivity extends TemplateActivity implements OnClickListener{
	private EditText mKeyword;
	private ImageButton mSearchButton;
	private ListView mResultList;
	private FindShopAction mAction;
	private CommonListAdapter mCommonListAdapter;
	private KeywordAdapter mKeywordListAdapter;
	private boolean sreachAlready;
	private boolean isShowResulte;
	private View mSearchPanel;
	private View mToolPanel;
	private TextView mTotalPanel;
	private Button mFilter;	
	private PopupWindow selLocPopWin;
	private Animation mRefremce;
	
	private OnClickListener mKeywordClick = new OnClickListener(){
		@Override
		public void onClick(View v) {
			String key = ((TextView)v.findViewById(R.id.tab_tx)).getText().toString();
			startSearch(key); 
			executeChange = false;
			mKeyword.setText(key);
			executeChange = true;
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_search_page);

		mKeyword = (EditText) findViewById(R.id.edit_keyword);
		mSearchButton = (ImageButton) findViewById(R.id.search);
		mSearchPanel = findViewById(R.id.search_body);
		mToolPanel = findViewById(R.id.classic_button_panel);
		mTotalPanel = (TextView)findViewById(R.id.total_label);
		mTotalPanel.setText(String.format(getString(R.string.cheap_label, "")));
//		mClassicButton = (Button) findViewById(R.id.classic_button);
//		mTwonButton = (Button) findViewById(R.id.town_button);
		mResultList = (ListView) findViewById(R.id.listView);
		
		mFilter = (Button) findViewById(R.id.sort);
		mFilter.setVisibility(View.VISIBLE); 
		mFilter.setOnClickListener(this);
		mSearchButton.setOnClickListener(this);
		mRefremce = AnimationUtils.loadAnimation(this, R.anim.anim_refence);
		
		// 注册初始化
		listenerInit();
		initAdapter();
		switchSearchPanelShowType(true);
		mKeywordListAdapter.setList(SearKeyDB.findList());
	}

	// 初始化列表
	private void initAdapter() {
		if (mCommonListAdapter != null) {
			return;
		}
		mKeywordListAdapter = new KeywordAdapter(this);
		mCommonListAdapter = new CommonListAdapter(this, mResultList);
		mCommonListAdapter.setIdisplayNetErrAndRefreshView(this);
		
		Location loc = MyBMapManager.getInstace(this).getMyLoation();

		if (loc == null) {
			loc = new Location("stander");
			loc.setLatitude(22.620000 * 1E6);
			loc.setLongitude(114.070000 * 1E6);
		}

		mKeywordListAdapter.setOnClickListener(mKeywordClick);
		mCommonListAdapter.setToolView(mToolPanel);
		mCommonListAdapter.setTotalView(mTotalPanel);
		setAction(loc);
	}

	private void setAction(Location loc) {
		mAction = new FindShopAction(loc.getLongitude(), loc.getLatitude(),
				false, 1, 10);
		mAction.setOrderStruct(true, false, false, false, false, false);
		mCommonListAdapter.setCallback(new Handler(){
			@Override
			public void handleMessage(Message msg) {
				if(msg.what == Constant.HANDLER_SCUCESS){
					ShopList result = (ShopList) msg.obj;
					if(result != null && result.shopList != null && result.shopList.size() > 0){
						int count = result.shopList.size();
						StringBuilder sb = new StringBuilder();
						for(int i = 0; i < count; i++){
							if(i == count - 1){
								sb.append(result.shopList.get(i).shopId);
								break;
							}
							
							sb.append(result.shopList.get(i).shopId + ",");
						}
						SearKeyDB.updateIndexOfShopId(mKeyword.getText().toString(), sb.toString());
					}
				} 
			}
		});
		mCommonListAdapter.setAction(mAction);
//		readSortRecord(mAction);
		
//		mResultList.setAdapter(mCommonListAdapter);
	}

	/**
	 * 加载上次筛选记录
	 * @param action
	 */
	private void readSortRecord(FindShopAction action) {
		FileInputStream fis = null;
		try {
			fis = openFileInput(Constant.SORT_RECODE_FILE_NAME);
			byte[] data = new byte[fis.available()];
			fis.read(data);
			JSONObject json = new JSONObject(new String(data));
			mAction.setAreaId(json.getInt(Constant.TAG_CITY));
			JSONArray jsonArray = json.getJSONArray(Constant.TAG_CATEGORYS);
			if(jsonArray != null && jsonArray.length() > 0){
				ArrayList<Integer> cids = new ArrayList<Integer>();
				for(int i = 0 ; i < jsonArray.length(); i++){
					cids.add(jsonArray.getInt(i));
				}
				mAction.setCatalogyIds(cids);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(fis != null){
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data == null){
			return;
		}
		// TODO Auto-generated method stub
		switch (requestCode) {
//		case SelCategoryActivity.CODE_REQUEST: {
//			 ArrayList<Integer> catecgorys = data.getIntegerArrayListExtra(Constant.TAG_CATEGORYS);
//			mAction.setCatalogyIds(catecgorys);
////			mCommonListAdapter.resetPageInfo();
//// 			mCommonListAdapter.reload();
//			sreachAlready = false;
//			break;
//		}
//		case SelCityActivity.CODE_REQUEST: {
//			Area area = (Area) data.getSerializableExtra(Constant.TAG_CITY);
//			mAction.setAreaId(area != null ? area.areaId : -1);
////			mCommonListAdapter.resetPageInfo();
//// 			mCommonListAdapter.reload();
//			sreachAlready = false;
//			break;
//		}
		case FilterActivity.CODE_REQUEST: {
            if(resultCode == Activity.RESULT_OK)
            {
            	Area area = (Area)data.getSerializableExtra(Constant.TAG_CITY);
            	ArrayList<Integer> mCateList = data.getIntegerArrayListExtra(Constant.TAG_CATEGORYS);
                // 这里不做非法判断，非法就是移除了原来的条件，其实也是正确的[zhaohua]
                mAction.setAreaId(area == null ?  -1 : area.areaId);                              	
                mAction.setCatalogyIds(mCateList);
                mAction.setKeyword(mKeyword.getText() != null ? mKeyword.getText().toString() : null);
                
                mCommonListAdapter.resetPageInfo();
    			mCommonListAdapter.reload();
                mCommonListAdapter.loadData();
            }
            break;
        }
		case HistoryActivity.CODE_REQUEST: {
			String keyword = data.getStringExtra(Constant.TAG_SREACH_HISTORY);
			mKeyword.setText(keyword);
			sreachAlready = true;
			mAction.setAreaId(-1);
			mAction.setCatalogyIds(null);
			mAction.setKeyword(keyword);
			startSearch(keyword); 
			break;
		}
		default:
			break;
		}
	}

	private void searchKeyword(String keyword) {
		mCommonListAdapter.resetPageInfo();
		mCommonListAdapter.reload();
		
		ConnectivityManager cManager =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cManager.getActiveNetworkInfo(); 
		if (info != null && info.isAvailable()) {
			mCommonListAdapter.loadData();
		} else {
			mCommonListAdapter.onLoaded(getDBShopByKeyword(keyword));
		}
		switchSearchPanelShowType(false);
		((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
	}

	@Override
	protected void setupTitleBar(TitleBar titleBar) {
		titleBar.setTitle(R.string.search_title);
		titleBar.setRigthBg(R.drawable.settings_icon_button);
		titleBar.setRigthImage(0);
//		titleBar.setCustomRightView(mRefremce);
		 
		titleBar.setOnTitleClickListener(new OnTitleClickListener() {
			// 历史记录管理
			public void onRightClick() {
				if(isShowResulte){
	                mCommonListAdapter.resetPageInfo();
	    			mCommonListAdapter.reload();
	                mCommonListAdapter.loadData();
	                if(mRefremce != null){
	                	mTitleBar.getRightImgView().startAnimation(mRefremce);
	                }
	                
				} else {
					((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
					showSelLocPopWin();
				}
			}

			// 返回主页面
			public void onLeftClick() {
				if(isShowResulte){
					switchSearchPanelShowType(true);
				} else {
					MainIndexActivity.gotoShake(SearchActivity.this,mTitleBar.getLeftImgView());
				}
			}

			
		}, true, true);
	}
	
	private void showSelLocPopWin()
    {
        if(selLocPopWin == null)
        {
            View contentView = LayoutInflater.from(this).inflate(R.layout.popview_settings_search, null);
            selLocPopWin = new PopupWindow(contentView,ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT, false);            
//            selLocPopWin.setBackgroundDrawable(new BitmapDrawable());
//            selLocPopWin.setFocusable(true);
            selLocPopWin.setTouchable(true);
            
            contentView.findViewById(R.id.search_cycle).setOnClickListener(this);
            contentView.findViewById(R.id.clear_history).setOnClickListener(this);
            contentView.findViewById(R.id.select_setting_search_week).setOnClickListener(this);
            contentView.findViewById(R.id.select_setting_search_month).setOnClickListener(this);
            contentView.findViewById(R.id.select_setting_search_year).setOnClickListener(this);
            
            contentView.findViewById(R.id.pop_cancel).setOnClickListener(this);
            
            int days = MyApplication.getContext().getKeywordSaveDays();
            int id = days == 7 ? R.id.select_setting_search_week_img : (days == 30 ? R.id.select_setting_search_month_img : (days == 365 ? R.id.select_setting_search_year_img : 0));
            
            setSelected(contentView, id);
        }
        selLocPopWin.showAtLocation(getWindow().getDecorView(),Gravity.BOTTOM, 0, 0);
    }
	
	@Override
	public void onBackPressed() {
		if(selLocPopWin != null && selLocPopWin.isShowing()){
			dissPop();
			return;
		}
		super.onBackPressed();
	}
	
    private void dissPop()
    {
        if(selLocPopWin != null && selLocPopWin.isShowing())
        {
            selLocPopWin.dismiss();
            selLocPopWin = null;
        }
    }
	
	private void switchSearchPanelShowType(boolean searchType) {
		//搜索界面
		if(searchType){
			mSearchPanel.setVisibility(View.VISIBLE);
			mToolPanel.setVisibility(View.GONE);
			mTotalPanel.setVisibility(View.GONE);
			mResultList.setAdapter(mKeywordListAdapter);
			mTitleBar.setRigthBg(R.drawable.settings_icon_button);
			mTitleBar.setTitle(R.string.search_title);
			mTitleBar.setRigthImage(0);
			isShowResulte = false;
		} 
		//搜索结果界面
		else {
			mSearchPanel.setVisibility(View.GONE);
			mToolPanel.setVisibility(View.VISIBLE);
			mTotalPanel.setVisibility(View.VISIBLE);
			mResultList.setAdapter(mCommonListAdapter);
			mTitleBar.setRigthBg(R.drawable.red_button_bg);
			mTitleBar.setRigthImage(R.drawable.refence_button_icon);
			mTitleBar.setTitle(R.string.search_result);
			isShowResulte = true;
		}
		
		mKeywordListAdapter.removeAll();
		mCommonListAdapter.removeAll();
		
	}
	
	private void startSearch(String value) {
		sreachAlready = true;
		mAction.setKeyword(value);
		if(!mResultList.getAdapter().equals(mCommonListAdapter)){
			mResultList.setAdapter(mCommonListAdapter);
		}
		searchKeyword(value);
	}
	
	private boolean executeChange = true;

	private void listenerInit() {
		mKeyword.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) { 
				if(!executeChange){
					return;
				}
				
				sreachAlready = false;
				if(!mResultList.getAdapter().equals(mKeywordListAdapter)){
					mResultList.setAdapter(mKeywordListAdapter);
				}
				
				if(s == null || s.length() == 0){
					mKeywordListAdapter.setList(SearKeyDB.findList());
					return;
				}
				
				mKeywordListAdapter.setList(SearKeyDB.getLikeKey(s.toString()));
			}
		});
//		// 搜索确认按键
//		mSearchButton.setOnClickListener(new OnClickListener() {
//			public void onClick(View v) {
//				String value = mKeyword.getText() != null ? mKeyword.getText().toString() : null;
//				if(value == null || sreachAlready){
//					return;
//				}
//				
//				SearKeyDB.saveKey(value);
//				startSearch(value); 
//				
//			}
//
//			
//		});
//		// 分类搜索修改页面
//		mClassicButton.setOnClickListener(new OnClickListener() {
//			public void onClick(View v) {
//				SelCategoryActivity.startActivityResult(SearchActivity.this,
//						true);
//			}
//		});
//		// 城镇搜素条件修改页面
//		mTwonButton.setOnClickListener(new OnClickListener() {
//			public void onClick(View v) {
//				SelCityActivity.startActivityResult(SearchActivity.this);
//			}
//		});
	}
	
	private List<Shop> getDBShopByKeyword(String key){
		List<Shop> list = new ArrayList<Shop>();
		List<Integer> ids = SearKeyDB.getIndexsByKey(key);
		Shop shop = null;
		ShopDetail sd = null;
		for(int i = 0; i < ids.size(); i++){
			sd = ShopDB.find(ids.get(i));
			if(sd == null){
				continue;
			}
			shop = new Shop();
			shop.shopDetail2Shop(this, sd);
			list.add(shop);
		}
		
		return list;
	}
	
	private void setSelected(View parent, int id) {
		if(id == 0){
			id = R.id.select_setting_search_month_img;
		}
		
		DataCache.setValue(Constant.LOCATION_TYPE, id);
		parent.findViewById(R.id.select_setting_search_week_img).setVisibility(
				View.GONE);
		parent.findViewById(R.id.select_setting_search_month_img)
				.setVisibility(View.GONE);
		parent.findViewById(R.id.select_setting_search_year_img).setVisibility(
				View.GONE);

		parent.findViewById(id).setVisibility(View.VISIBLE);
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
	    switch(v.getId())
	    {
    	    case R.id.sort:
    	    {
    	        FilterActivity.startActivityResult(this);
    	        break;
    	    } 
    	    case R.id.search:
    	    {
    	    	String value = mKeyword.getText() != null ? mKeyword.getText().toString() : null;
				if(value == null){
					return;
				}
				
				SearKeyDB.saveKey(value);
				startSearch(value); 
				break;
    	    }
    	    case R.id.search_cycle:
    	    {
    	    	selLocPopWin.getContentView().findViewById(R.id.one_list).setVisibility(View.GONE);
    	    	selLocPopWin.getContentView().findViewById(R.id.two_list).setVisibility(View.VISIBLE);
    	        break;
    	    } 
    	    case R.id.clear_history:
    	    {
    	    	
    	    	AlertDialog.Builder builder = new Builder(this);
    	        builder.setMessage(R.string.clear_history_all);
    	        builder.setTitle(R.string.shortcut_notify);
    	        builder.setPositiveButton(R.string.sure,
    	                new DialogInterface.OnClickListener()
    	                {
    	                    public void onClick(DialogInterface dialog, int which)
    	                    {
    	                    	SearKeyDB.clear(SearKeyDB.TABLE_NAME, null);
    	            	    	dissPop();
    	            	    	mKeywordListAdapter.removeAll();
    	            	    	showToast(getString(R.string.select_setting_clear_text));
    	                    }
    	                });

    	        builder.setNegativeButton(R.string.cancel,
    	                new DialogInterface.OnClickListener()
    	                {
    	                    public void onClick(DialogInterface dialog, int which)
    	                    {
    	                        dialog.dismiss();
    	                    }
    	                });

    	        builder.create().show();
				break;
    	    }
    	    case R.id.select_setting_search_week:
    	    {
    	    	MyApplication.getContext().setKeywordSaveDays(7);
    	    	setSelected(selLocPopWin.getContentView(), R.id.select_setting_search_week_img);
    	    	dissPop();
    	        break;
    	    } 
    	    case R.id.select_setting_search_month:
    	    {
    	    	MyApplication.getContext().setKeywordSaveDays(30);
    	    	setSelected(selLocPopWin.getContentView(), R.id.select_setting_search_month_img);
    	    	dissPop();
    	        break;
    	    } 
    	    case R.id.select_setting_search_year:
    	    {
    	    	MyApplication.getContext().setKeywordSaveDays(365);
    	    	setSelected(selLocPopWin.getContentView(), R.id.select_setting_search_year_img);
    	    	dissPop();
    	        break;
    	    } 
    	    case R.id.pop_cancel:
    	    {
    	    	dissPop();
				break;
    	    }
    	    
	    }
		
	}
}
